package com.brotherly.framework.event;

import java.util.HashMap;
import java.util.Map;

public abstract class EventListenerHelper implements EventListener
{
    protected static class EventStub
    {
        public String eventid;
        public int stub;
        public int count;

        public static EventStub create(String eventid, int stub)
        {
            EventStub eventStub = new EventStub();

            eventStub.eventid = eventid;
            eventStub.stub = stub;
            eventStub.count = 1;

            return eventStub;
        }
    }

    protected EventService service;
    protected Map<String, EventStub> stubs;

    public EventListenerHelper()
    {
        stubs = new HashMap<String, EventStub>();
    }

    public EventService getService()
    {
        return service;
    }

    public void setService(EventService service)
    {
        this.service = service;
    }

    public synchronized int attahEvent(String eventid)
    {
        EventStub stub = null;

        stub = stubs.get(eventid);
        if (stub != null)
        {
            ++stub.count;
            return stub.stub;
        }

        try
        {
            int result = service.registerEventListener(eventid, this);

            stub = EventStub.create(eventid, result);
            stubs.put(eventid, stub);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return stub.stub;
    }

    public synchronized void detachEvent(String eventid)
    {
        EventStub stub = stubs.get(eventid);

        if (stub != null && --stub.count == 0)
        {
            try
            {
                service.unregisterEventListener(stub.eventid, stub.stub);
                stubs.remove(eventid);
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
}
